package com.sheliduan.itlearning.common.utils;

import com.sheliduan.itlearning.common.exception.BaseExceptionInterface;
import com.sheliduan.itlearning.common.exception.BizException;
import lombok.Data;

import java.io.Serializable;

/**
 * @author: 断舍离
 * @date: 2025/1/21 9:31
 * @description: 统一响应数据类, 失败响应无data
 **/
@Data
public class ResponseData<T> implements Serializable {

    // 响应是否成功, 默认为true
    private boolean success = true;

    // 响应消息
    private String message;

    // 错误状态码
    private String errorCode;

    // 响应数据
    private T data;

    /*
    * 成功响应, 不设置响应数据
    * */
    public static <T> ResponseData<T> success(){
        return new ResponseData<>();
    }

    /*
     * 成功响应, 设置响应数据
     * */
    public static <T> ResponseData<T> success(T data){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setData(data);
        return responseData;
    }

    /*
    * 失败响应, 不设置响应消息和错误状态码
    * */
    public static <T> ResponseData<T> fail(){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setSuccess(false);
        return responseData;
    }

    /*
     * 失败响应, 只设置错误响应消息
     * */
    public static <T> ResponseData<T> fail(String errorMessage){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setSuccess(false);
        responseData.setMessage(errorMessage);
        return responseData;
    }

    /*
     * 失败响应, 只设置错误状态码和错误响应消息
     * */
    public static <T> ResponseData<T> fail(String errorCode, String errorMessage){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setSuccess(false);
        responseData.setErrorCode(errorCode);
        responseData.setMessage(errorMessage);
        return responseData;
    }

    /*
     * 失败响应, 传入业务异常类对象, 然后设置错误响应的属性
     * */
    public static <T> ResponseData<T> fail(BizException bizException) {
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setSuccess(false);
        responseData.setErrorCode(bizException.getErrorCode());
        responseData.setMessage(bizException.getErrorMessage());
        return responseData;
    }

    /*
     * 失败响应, 传入错误枚举类型(BaseExceptionInterface的子枚举)
     * */
    public static <T> ResponseData<T> fail(BaseExceptionInterface baseExceptionInterface) {
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setSuccess(false);
        responseData.setErrorCode(baseExceptionInterface.getErrorCode());
        responseData.setMessage(baseExceptionInterface.getErrorMessage());
        return responseData;
    }
}
